package cn.szzsi._webpc;


import cn.szzsi._web.BaseWebController;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.model.Member;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 前台类 - 密码、安全问题
 *
 */
public class PasswordController extends BaseWebPcController<Member> {

	private Member member;
	//private String oldPassword;
	private String path;//模板路径
	private String shopId;//用户的shopId就是商户的id
	
	// 密码修改
	public void edit() {
		shopId=getLoginMember().getStr("shopId");//用户的shopId对应商户的id(uid),商户的shopId为0
		setAttr("shopId",shopId);
		setAttr("member", getLoginMember());
		pcTemplatePath("password_input.html");
	}
	
	// 密码更新
//	@Before(PasswordValidator.class)
	@Before(Tx.class)
	public void update() {
		member = getModel(Member.class);
		String oldPassword = getPara("oldPassword","");//旧密码
		String rePassword=getPara("rePassword");//确认新密码
		if(StrKit.isBlank(member.getPassword())){
			renderHtml("<script>alert('新密码不允许为空!');history.go(-1);</script>");
			return;
		}
		if(!member.getPassword().equals(rePassword)){
			renderHtml("<script>alert('两次密码输入不一致!');history.go(-1);</script>");
			return;
		}

		Member persistent = getLoginMember();
		String shopid = getPara("shopid");
		if (StrKit.notBlank(oldPassword) && StrKit.notBlank(member.getPassword())) {
			String oldPasswordMd5 = DigestUtils.md5Hex(oldPassword);
			if (!StringUtils.equals(persistent.getStr("password"), oldPasswordMd5)) {
				renderHtml("<script>alert('旧密码不正确!');history.go(-1);</script>");
				return;
			}
			String newPasswordMd5 = DigestUtils.md5Hex(member.getStr("password"));
			persistent.set("password",newPasswordMd5);
		}
		if (StrKit.notBlank(member.getStr("safeQuestion")) && StrKit.notBlank(member.getStr("safeAnswer"))) {
			persistent.set("safeQuestion",member.getStr("safeQuestion"));
			persistent.set("safeAnswer",member.getStr("safeAnswer"));
		}
		
		updated(persistent);
		redirect("/b/pc/password/edit");
		//renderWapSuccessMessage("更新成功!","/b/pc/password/edit?shopId="+shopid,path);
	}
}
